import time
import copy
import hmac
import hashlib
import base64
import urllib.parse
import click
import requests
import subprocess
from multiprocessing import Pool
from pathlib import Path
import ddRobot


def ddsecret():
    timestamp = str(round(time.time() * 1000))
    t = time.localtime()
    date = f'{t.tm_hour:02}:{t.tm_min:02}'
    secret = 'SEC9cecc2366ca1e3728625861c39ab71be4dfe1afccd71cdca2f8fd1ddd95f6943'
    secret_enc = secret.encode('utf-8')
    string_to_sign = f'{timestamp}\n{secret}'
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc,
                         digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return timestamp, sign, date


def dealSampleSheet(samplesheet):
    with open(samplesheet) as ssf:
        _samples = []
        flag = 0
        for i in ssf:
            if flag == 0:
                if i.startswith('Sample_ID'):
                    flag = 1
                    continue
                continue
            if flag == 1:
                _samples.append(i.split(',')[0])
        return _samples


def runSH(sh):
    a = subprocess.run(f'sh {sh}', shell=True, stderr=subprocess.PIPE)


@click.command()
@click.option('-ss', '--samplesheet', required=True, type=str, help="samplesheet file of bcl2fastq")
@click.option('-id', '--inputdir', required=True, type=str, help="out path")
@click.option('-t', '--thread', default=4, type=int, help="sample thread")
@click.option('-l', '--location', default='zz', type=str, help="sample location")
def main(samplesheet, inputdir, thread, location):
    samples = dealSampleSheet(samplesheet)
    outdir = Path(inputdir)
    outdir = outdir.absolute()
    if location == 'zz':
        location = '郑州'
    elif location == 'fz':
        location = '福州'
    elif location == 'cs':
        location = '长沙'
    elif location == 'bj':
        location = '北京'
    # ddRobot.robot(f'{location} blast NT 等待运行......', 'FZQ')

    p = Pool(thread)
    parses = copy.deepcopy(samples)
    while 1:
        for i, e in enumerate(samples):
            iterSH = outdir.glob(f'{e}.*.sh')
            try:
                sampleSH = next(iterSH)
                time.sleep(5)
                samples.pop(i)
                p.apply_async(runSH, (sampleSH,))
            except Exception as e:
                print(e)
                pass
        for i, e in enumerate(parses):
            parsefile = outdir.glob(f'{e}.*.parse.xls')
            try:
                next(parsefile)
                parses.pop(i)
                timestamp, sign, date = ddsecret()
                headers = {'Content-Type': 'application/json'}
                url = f'https://oapi.dingtalk.com/robot/send?access_token=c88766070cf41652b80038f773f20a92bbc1b1439d1abc4602f946fa68ad89a3&timestamp={timestamp}&sign={sign}'
                json={
                    "msgtype": "text",
                    "text": { "content": f"{date} {location} {e} blastNT结果已出《《《" }
                    }
                requests.post(url=url,headers=headers,json=json)
            except:
                pass
        if not samples and not parses:
            break
        time.sleep(60)
    p.close()
    p.join()
    #ddRobot.robot(f'{location} blast NT 运行完毕！', 'FZQ')
    ddRobot.robot(f'{location} blast NT 运行完毕！', 'WHQ')

if __name__ == "__main__":
    main()
